import requests
import json
import hashlib
from time import time
from app.taobao_api import config
from flask import current_app
# import byte2hex

class Logistics_Dummy_Send():
    # TODO 物流发货
    def __init__(self, tid, token):
        self.url = config.UPDATE_LogisticsDummy_URL
        self.tid = tid
        self.appsecret = config.APPSECRET
        self.headers = {
            'Authorization': 'Bearer ' + token,
            'ApiVersion': '1'
        }

    def signstr(self, pre_body):  # 签名算法
        sign_str = self.appsecret
        for key, value in pre_body.items():
            sign_str += key + value
        sign_str += self.appsecret
        md5 = hashlib.md5()
        md5.update(sign_str.encode('utf-8'))
        return md5.hexdigest()

    @property
    def validate_tid(self):  # 验证订单号
        current_time = str(int(time()))
        pre_body = {
            'tids': self.tid,
            'timestamp': current_time
        }
        body = {
            'tids': self.tid,
            'timestamp': current_time,
            'sign': self.signstr(pre_body)
        }
        try:
            r = requests.post(self.url, headers=self.headers, data=body)
        except Exception as e:
            print(e)
            return -2
        dictinfo = json.loads(r.text)
        if dictinfo['Error_Code'] == 0:
            return True
        else:
            return dictinfo['Error_Msg']


if __name__ == '__main__':
    s = Logistics_Dummy_Send('283606797224137500')
    print(s.validate_tid)
